#!/usr/bin/env python
# -*- coding:utf-8 -*-

import web

#使用mako模板
from web.contrib.template import render_mako

from conf import Fetion
from weather import Weather
from PyFetion import *

urls = ( '/', 'index',
        '/login', 'Login',
        '/logout', 'Logout',
        '/admin', 'Admin',
        '/donew', 'DoNew',
        '/petition', 'Petition',
        '/addnew', 'AddNew',
        '/deluser', 'DelUser',
        '/addtarget', 'AddTarget',
        '/deltarget', 'DelTarget',
        '/addcity', 'AddCity',
        '/delcity', 'DelCity',
        '/send-msg-to-phone-by-pyfetion', 'Send',
        )

web.config.debug = True
app = web.application(urls, globals())
db = web.database(dbn="sqlite", db="weap.db")

## 非Debug模式下使用session
#session = web.session.Session(
#    app,
#    web.session.DiskStore('sessions'),
#    initializer = {
#        "login": 0,
#        "name": None
#        }
#    )

#调试模式下使用session
if web.config.get('_session') is None:
    session = web.session.Session(
        app,
        web.session.DiskStore('sessions'),
        initializer = {
            "login": 0,
            "name": None
            }
        )
    web.config._session = session
else:
    session = web.config._session

#render = web.template.render("templates/")  # 使用自带模板系统

## 使用Mako模板
render = render_mako(
            directories=['templates'],
            input_encoding='utf-8',
            output_encoding='utf-8',
            )


def logged():
    # 判断是否已登录
    if session.login:
        return True
    else:
        return False


class index:
    """首页"""
    def GET(self):
        citys = list(db.select("city"))
        return render.index(citys=citys)


class Login:
    """登录后台"""
    def GET(self):
        print logged()
        if logged():
            raise web.seeother('/admin')
        else:
            return render.login()

    def POST(self):
        username, pwd = web.input().user, web.input().pwd
        result = list(db.query("select * from admin where username=$name and pwd=$pwd",
            vars = {"name": username, "pwd": pwd}))
        if result:
            session.login = 1
            session.username = username
            raise web.redirect('/admin')
        else:
            raise web.seeother('/')


class Logout:
    """退出管理后台"""
    def GET(self):
        session.login = 0
        session.kill()
        raise web.seeother('/')

class Admin:
    """管理后台"""
    def GET(self):
        if logged()==0:
            raise web.seeother('/login')
        else:
            newers = list(db.select("newuser"))
            users = list(db.select("user"))
            citys = list(db.select("city"))
            targets = list(db.select("target"))
            return render.admin(newers=newers,
                                users=users,
                                citys=citys,
                                targets=targets
                                )


class Petition:
    """首页用户提交申请"""
    def POST(self):
        try:
            phone, city, msg = web.input().phone, web.input().city, web.input().msg
            db.insert("newuser", phone=phone, city=city, msg=msg)

            raise web.seeother('/')
        except:
            return 'error...'


class DoNew:
    """处理首页用户的申请，目前还没有实现全自动的处理.
       这中间涉及到添加飞信好友、添加用户信息、添加发送目标信息等。
       目前的方式是看到申请后手动进行上面的申请操作，然后这里删除用户的申请信息。
    """
    def GET(self):
        try:
            db.delete("newuser", where="id=$id", vars={"id": web.input().id})
            raise web.seeother('/admin')
        except:
            return 'error...'


class AddNew:
    """添加正式订阅的用户信息"""
    def POST(self):
        i = web.input()
        sip,nick,cell,city = i.sip,i.nick,i.cell,i.city
        try:
            db.insert("user", fetionsip=sip, nickname=nick, cellphone=cell)
            db.insert("target", sip=sip, city=city)

            raise web.seeother('/admin')
        except:
            return "error..."


class DelUser:
    """删除已订阅的用户，如果要取消发送消息需要先删除订阅城市信息再删用户"""
    def GET(self):
        try:
            userid = web.input().id
            db.delete('user', where="userid=$userid", vars={'userid':userid})

            raise web.seeother('/admin')
        except:
            return "error..."


class AddTarget:
    """添加用户订阅的目标城市"""
    def GET(self):
        try:
            fetionsip = web.input().sip
            citys = list(db.select("city"))
            return render.addtarget(fetionsip=fetionsip, citys=citys)
        except:
            return "error..."

    def POST(self):
        try:
            sip,city = web.input().sip, web.input().city
            db.insert("target", sip=sip, city=city)
            raise web.seeother('/admin')
        except:
            return "error..."


class DelTarget:
    """删除用户订阅的目标城市"""
    def GET(self):
        sip,city = web.input().sip, web.input().city
        db.delete("target", where="sip=$sip and city=$city", vars={"sip":sip, "city":city})
        raise web.seeother('/admin')


class AddCity:
    """添加城市信息"""
    def POST(self):
        cityname, uri = web.input().cityname, web.input().uri
        db.insert("city", cityname=cityname, uri=uri)
        raise web.seeother('/admin')


class DelCity:
    """删除多余的城市信息"""
    def GET(self):
        cityid = web.input().id
        db.delete("city", where="cityid=$cityid", vars={"cityid":cityid})
        raise web.seeother('/admin')


class Send:
    """Cron Task"""
    def GET(self):
        fetion = PyFetion(Fetion.fetion_id, Fetion.fetion_pwd, "HTTP")
        fetion.login(FetionHidden)

        users = list(db.select("user"))  # 先按顺序抓取用户信息获取飞信号
        for user in users:
            sip = user.fetionsip

            targets = list(db.select("target", where="sip=$sip", vars={"sip":sip}))  # 获取该用户订阅的城市
            outlet = ["天气预报"]  # 格式化输出内容
            for target in targets:
                city = target.city

                # 获取目标城市对应的信息源地址
                urls = list(db.select("city", where="cityname=$city", vars={"city":city}))
                city = city.encode('utf-8','ignore')
                uri = urls[0].uri

                # 抓取天气信息
                weapho = Weather(city, uri)
                outlet.append(weapho.GetWeather())

            message = "\n".join(outlet)
            fetion.send_sms(message, sip, True)

        fetion.logout()
        return "Done."

if __name__ == "__main__":
    app.run()
